import React, { Component, PropTypes } from "react";
import { getSubText, messages } from "share/common";
import { Input } from "antd";
import InputBankCardService from "components/template/input-bank-card/input-bank-card.service";
import debounce from "lodash.debounce";

class InputBankCard extends Component {
  state = {
    preBankName: "",
  };

  componentDidMount() {
    this.realGetPossibleBankName = debounce(this.realGetPossibleBankName, 300);
    this.tempFirst = "";
  }

  handleKeyDown = (e) => {
    this.props.onChange && this.props.onChange(e);
    this.getPossibleBankName(e.target.value);
  };

  getPossibleBankName = (value) => {
    if (typeof value === "string" && value.length >= 6) {
      if (this.tempFirst === getSubText(value, 6)) {
      } else {
        this.tempFirst = getSubText(value, 6);
        this.realGetPossibleBankName(this.tempFirst);
      }
    } else {
      this.setState({
        preBankName: "",
      });
    }
  };

  realGetPossibleBankName = (firstSixNum) => {
    InputBankCardService.getPossibleBank({ code: firstSixNum })
      .then((res) => {
        if (res.status === 200) {
          const data = res.data && res.data[0];
          if (data) {
            this.setState({ preBankName: data.name });
          } else {
            this.setState({ preBankName: "" });
          }
        } else {
          this.setState({ preBankName: "" });
        }
      })
      .catch(() => {
        this.setState({ preBankName: "" });
      });
  };

  render() {
    return (
      <div style={this.props.style || { width: "66%" }}>
        <Input
          value={this.props.value}
          disabled={this.props.disabled}
          onChange={this.handleKeyDown}
          placeholder={messages("common.please.input") /*请输入*/}
        />
        {this.state.preBankName && (
          <div>
            {messages("common-1.key1369") /*当前卡号可能为：*/}
            {this.state.preBankName}
          </div>
        )}
      </div>
    );
  }
}

//必填校验
InputBankCard.rules = (length, isRequired) => {
  const result = [
    {
      message: messages("basic-8.key50") /*必须包含数字*/,
      validator: (rule, value, cb) => {
        if (value === null || value === undefined || value === "") {
          cb();
          return;
        }
        const regExp = /[0-9]/;
        //去掉空格
        value = value.replace(/ /g, "");
        if (regExp.test(value)) {
          cb();
        } else {
          cb(false);
        }
      },
    },
    {
      max: length,
      message: messages("common.max.characters.length", {
        arg1: length,
      }) /*最多输入{arg1}个字符*/,
    },
  ];
  if (isRequired)
    result.push({
      required: true,
      message: messages("common.please.input") /*请输入*/,
    });
  return result;
};

export default InputBankCard;
